import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getCourseApplications, reviewCourseApplication } from '../../api/admin';
import { message } from 'antd';

function Badge({ status }) {
  const statusMap = {
    'pending': { text: '待审批', bg: '#fffbe6', border: '#ffe58f', textColor: '#faad14' },
    'approved': { text: '已通过', bg: '#f6ffed', border: '#b7eb8f', textColor: '#52c41a' },
    'rejected': { text: '已拒绝', bg: '#fff1f0', border: '#ffccc7', textColor: '#ff4d4f' }
  };
  const style = statusMap[status] || statusMap['pending'];
  return (
    <span style={{ 
      color: style.textColor, 
      background: style.bg, 
      padding: '4px 12px', 
      borderRadius: 12, 
      border: `1px solid ${style.border}`, 
      fontSize: 12,
      display: 'inline-block'
    }}>
      {style.text}
    </span>
  );
}

function Review() {
  const [q, setQ] = useState('');
  const [statusFilter, setStatusFilter] = useState('所有状态');
  const [active, setActive] = useState(null);
  const queryClient = useQueryClient();

  // 状态映射
  const statusMap = {
    '所有状态': undefined,
    '待审批': 'pending',
    '已通过': 'approved',
    '已拒绝': 'rejected'
  };

  // 获取课程申请列表
  const { data: applications = [], isLoading } = useQuery({
    queryKey: ['admin', 'courseApplications', statusMap[statusFilter]],
    queryFn: () => getCourseApplications(statusMap[statusFilter]),
    retry: false, // 不重试，失败直接使用mock
    // 注意：tryApiOrMock 已经处理了错误并降级到 mock，不会抛出异常
  });

  // 审核课程申请
  const reviewMutation = useMutation({
    mutationFn: ({ id, status, reason }) => reviewCourseApplication(id, { status, reason }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'courseApplications'] });
      message.success('审核完成');
      setActive(null);
    },
    onError: (error) => {
      message.error(error.message || '审核失败，请重试');
    },
  });

  // 过滤数据
  const filteredData = applications.filter(r => 
    (!q || r.name.toLowerCase().includes(q.toLowerCase()))
  );

  const openModal = (item) => setActive(item);
  const closeModal = () => setActive(null);

  const handleApprove = () => {
    if (active) {
      reviewMutation.mutate({
        id: active.id,
        status: 'approved',
        reason: '审核通过'
      });
    }
  };

  const handleReject = () => {
    if (active) {
      reviewMutation.mutate({
        id: active.id,
        status: 'rejected',
        reason: '审核不通过'
      });
    }
  };

  return (
    <div style={{ padding: '20px 16px 100px 16px' }}>
      <div style={{ fontSize: 20, fontWeight: 600, marginBottom: 16, color: '#222' }}>课程申请审核</div>
      <div style={{ background: '#fff', borderRadius: 10, boxShadow: '0 1px 6px #f0f1f3', padding: 16, marginBottom: 16, display: 'flex', gap: 12 }}>
        <input 
          value={q} 
          onChange={e => setQ(e.target.value)} 
          placeholder="搜索课程名称..." 
          style={{ 
            flex: 1, 
            padding: '10px 12px', 
            border: '1px solid #e5e7eb', 
            borderRadius: 6,
            fontSize: 14
          }} 
        />
        <select 
          value={statusFilter} 
          onChange={e => setStatusFilter(e.target.value)} 
          style={{ 
            padding: '10px 12px', 
            borderRadius: 6, 
            border: '1px solid #e5e7eb',
            fontSize: 14,
            minWidth: 120,
            background: '#fff'
          }}
        >
          <option>所有状态</option>
          <option>待审批</option>
          <option>已通过</option>
          <option>已拒绝</option>
        </select>
      </div>
      <div style={{ background: '#fff', borderRadius: 10, boxShadow: '0 1px 6px #f0f1f3', overflow: 'hidden' }}>
        {isLoading ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#999' }}>加载中...</div>
        ) : filteredData.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#999' }}>暂无数据</div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: '#f7f9fc' }}>
                <th style={{ textAlign: 'left', padding: 14, fontSize: 14, fontWeight: 500, color: '#444' }}>课程名称</th>
                <th style={{ textAlign: 'left', padding: 14, fontSize: 14, fontWeight: 500, color: '#444' }}>任课教师</th>
                <th style={{ textAlign: 'left', padding: 14, fontSize: 14, fontWeight: 500, color: '#444' }}>教师工号</th>
                <th style={{ textAlign: 'left', padding: 14, fontSize: 14, fontWeight: 500, color: '#444' }}>学分</th>
                <th style={{ textAlign: 'left', padding: 14, fontSize: 14, fontWeight: 500, color: '#444' }}>容量</th>
                <th style={{ textAlign: 'left', padding: 14, fontSize: 14, fontWeight: 500, color: '#444' }}>申请时间</th>
                <th style={{ textAlign: 'left', padding: 14, fontSize: 14, fontWeight: 500, color: '#444' }}>状态</th>
              </tr>
            </thead>
            <tbody>
              {filteredData.map(r => (
                <tr 
                  key={r.id} 
                  style={{ 
                    borderTop: '1px solid #f0f1f3', 
                    cursor: 'pointer',
                    transition: 'background 0.2s'
                  }} 
                  onClick={() => openModal(r)}
                  onMouseEnter={(e) => e.currentTarget.style.background = '#f5f5f5'}
                  onMouseLeave={(e) => e.currentTarget.style.background = '#fff'}
                >
                  <td style={{ padding: 14, color: '#222', fontSize: 14 }}>{r.name}</td>
                  <td style={{ padding: 14, color: '#666', fontSize: 14 }}>{r.teacherName}</td>
                  <td style={{ padding: 14, color: '#666', fontSize: 14 }}>{r.teacherAccount}</td>
                  <td style={{ padding: 14, color: '#666', fontSize: 14 }}>{r.credit}学分</td>
                  <td style={{ padding: 14, color: '#666', fontSize: 14 }}>{r.capacity}</td>
                  <td style={{ padding: 14, color: '#666', fontSize: 14 }}>{r.applyDate}</td>
                  <td style={{ padding: 14 }}><Badge status={r.status} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {active && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.25)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 200 }}>
          <div style={{ width: 520, background: '#fff', borderRadius: 12, boxShadow: '0 12px 40px rgba(0,0,0,0.12)', overflow: 'hidden' }}>
            <div style={{ padding: '16px 18px', borderBottom: '1px solid #f0f0f0', fontWeight: 600 }}>课程申请详情</div>
            <div style={{ padding: 18 }}>
              <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 8 }}>{active.name}</div>
              <div style={{ color: '#606266', marginBottom: 6 }}>任课教师：{active.teacherName}</div>
              <div style={{ color: '#606266', marginBottom: 6 }}>教师工号：{active.teacherAccount}</div>
              <div style={{ color: '#606266', marginBottom: 6 }}>学分：{active.credit}</div>
              <div style={{ color: '#606266', marginBottom: 6 }}>容量：{active.capacity}</div>
              <div style={{ color: '#606266', marginBottom: 6 }}>申请时间：{active.applyDate}</div>
              <div style={{ color: '#606266', marginBottom: 6 }}>状态：<Badge status={active.status} /></div>
            </div>
            <div style={{ padding: '12px 18px', borderTop: '1px solid #f0f0f0', display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
              <button 
                onClick={() => closeModal()} 
                style={{ border: '1px solid #e5e7eb', background: '#fff', borderRadius: 6, padding: '8px 16px', cursor: 'pointer' }}
              >
                返回
              </button>
              {active.status === 'pending' && (
                <>
                  <button 
                    onClick={handleReject}
                    disabled={reviewMutation.isPending}
                    style={{ 
                      border: '1px solid #ffccc7', 
                      background: '#fff1f0', 
                      color: '#ff4d4f', 
                      borderRadius: 6, 
                      padding: '8px 16px', 
                      cursor: reviewMutation.isPending ? 'not-allowed' : 'pointer',
                      opacity: reviewMutation.isPending ? 0.6 : 1
                    }}
                  >
                    {reviewMutation.isPending ? '处理中...' : '不通过'}
                  </button>
                  <button 
                    onClick={handleApprove}
                    disabled={reviewMutation.isPending}
                    style={{ 
                      border: 0, 
                      background: '#52c41a', 
                      color: '#fff', 
                      borderRadius: 6, 
                      padding: '8px 16px', 
                      cursor: reviewMutation.isPending ? 'not-allowed' : 'pointer',
                      opacity: reviewMutation.isPending ? 0.6 : 1
                    }}
                  >
                    {reviewMutation.isPending ? '处理中...' : '通过'}
                  </button>
                </>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
export default Review;
